//
//  RecommendViewController.m
//  FourthProject
//
//  Created by mac on 16/5/25.
//  Copyright © 2016年 cry. All rights reserved.
//

#import "RecommendViewController.h"

#import "GuideBookViewController.h"
#import "SkimWebViewController.h"

#import "OneTableViewCell.h"
#import "TwoTableViewCell.h"
#import "ThreeTableViewCell.h"
#import "FourTableViewCell.h"

#import "DiscountObject.h"
#import "TravelObject.h"

@interface RecommendViewController ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,UIGestureRecognizerDelegate>
{
    SDCycleScrollView              *_cycleScroll;
    
    NSMutableArray                 *_scrollViewArray;
    NSMutableArray                 *_subjectArray;
    NSMutableArray                 *_discountSubArray;
    NSMutableArray                 *_discountArray;
    
    NSMutableArray                 *_otherArray;
    NSMutableArray                 *_tempArray;
    
    MJRefreshBackFooter            *_footer;
    int                            _page;
    
}
@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self getData];
    
    
    
    //_myTable.allowsSelection = NO;
    [_myTable registerClass:[UITableViewCell class] forCellReuseIdentifier:@"zero"];
    [_myTable registerNib:[UINib nibWithNibName:@"OneTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"one"];
    [_myTable registerNib:[UINib nibWithNibName:@"TwoTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"two"];
    [_myTable registerNib:[UINib nibWithNibName:@"ThreeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"three"];
    [_myTable registerNib:[UINib nibWithNibName:@"FourTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"four"];
    

    _page = 1;
    _footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self refreshData];
    }];
    _myTable.mj_footer = _footer;

}

- (void)refreshData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:@{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"v":@"1",@"track_deviceid":@"869070029694844",@"track_app_version":@"6.9.0",@"track_app_channel":@"xiaomi",@"track_device_info":@"lte26007",@"track_os":@"Android4.4.4",@"app_installtime":@"1463542775388",@"lat":@"24.548208",@"lon":@"118.1244",@"type":@"index",@"page":@"1",@"count":@"10"}];
    [dic setObject:[NSString stringWithFormat:@"%d",_page] forKey:@"page"];
    
    [manager GET:@"http://open.qyer.com/qyer/recommands/trip" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [_myTable.mj_footer endRefreshing];
        
        _tempArray = [TravelObject mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        [_otherArray addObjectsFromArray:_tempArray];
        
        [_myTable reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"!!!!!%@",error);
    }];
    
}

- (void)getData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSDictionary *dic1 = @{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"v":@"1",@"track_deviceid":@"869070029694844",@"track_app_version":@"6.9.0",@"track_app_channel":@"xiaomi",@"track_device_info":@"lte26007",@"track_os":@"Android4.4.4",@"app_installtime":@"1463542775388",@"channel":@"xiaomi HTTP/1.1"};
    
    [manager GET:@"http://open.qyer.com/qyer/recommands/entry" parameters:dic1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        _scrollViewArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"][@"slide"]];
        _subjectArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"][@"subject"]];
        _discountSubArray = [[NSMutableArray alloc] initWithArray:responseObject[@"data"][@"discount_subject"]];
        
        _discountArray = [DiscountObject mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"discount"]];
        
        [_myTable reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"!!!!!!%@",error);
    }];
    
    
    NSDictionary *dic2 = @{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"v":@"1",@"track_deviceid":@"869070029694844",@"track_app_version":@"6.9.0",@"track_app_channel":@"xiaomi",@"track_device_info":@"lte26007",@"track_os":@"Android4.4.4",@"app_installtime":@"1463542775388",@"lat":@"24.548208",@"lon":@"118.1244",@"type":@"index",@"page":@"1",@"count":@"10"};
    
    [manager GET:@"http://open.qyer.com/qyer/recommands/trip" parameters:dic2 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        _otherArray = [TravelObject mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        
        [_myTable reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}

- (void)buttonClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    switch (button.tag) {
        case 20:
        {
            GuideBookViewController *guideBookVC = [[GuideBookViewController alloc] init];
            
            [self.controller.navigationController pushViewController:guideBookVC animated:YES];
        }
            break;
        case 21:
        {
            NSLog(@"抢折扣");
        }
            break;
        case 22:
        {
            NSLog(@"订酒店");
        }
            break;
        case 23:
        {
            NSLog(@"旅途中");
        }
            break;
        default:
            break;
    }
}

- (void)ADButtonClick {
    NSLog(@"广告时间");
}


#pragma mark ---SDCycleScroll
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    SkimWebViewController *skimWebVC = [[SkimWebViewController alloc] init];
    
    skimWebVC.http = _scrollViewArray[index][@"url"];
    
    [self presentViewController:skimWebVC animated:YES completion:nil];
}


#pragma mark  tableView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = nil;
    
    if (section == 0) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 250)];
        headerView.backgroundColor = [UIColor yellowColor];
        
        NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
        for (int i = 0; i < _scrollViewArray.count; i++) {
            [arr addObject:_scrollViewArray[i][@"photo"]];
        }
        _cycleScroll = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 150) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
        _cycleScroll.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
        _cycleScroll.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
        _cycleScroll.imageURLStringsGroup = arr;
        [headerView addSubview:_cycleScroll];
        
        float w = (WIDTH - 10 * 5) / 4;
        float inset = 10;
        NSArray *arr1 = @[@"看锦囊",@"抢折扣",@"订酒店",@"旅途中"];
        NSArray *arr2 = @[@"景点_Small@2x",@"美食_Small@2x",@"扎点_Small_Pressed@2x",@"Recommend_Location_Loading_13"];
        
        for (int i = 0; i < 4; i++) {
            UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
            btn1.frame = CGRectMake(inset + (inset + w) * i , 150 + 10, w, w);
            btn1.backgroundColor = [UIColor yellowColor];
            btn1.layer.cornerRadius = w / 2;
            btn1.clipsToBounds = YES;
            btn1.tag = 20 + i;
            [btn1 setBackgroundImage:[UIImage imageNamed:arr2[i]] forState:UIControlStateNormal];
            [btn1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:btn1];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(inset + (inset + w) * i, 150 + 10 + w + 5, w, 20)];
            label.text = arr1[i];
            label.textAlignment = NSTextAlignmentCenter;
            label.textColor = [UIColor redColor];
            label.font = [UIFont systemFontOfSize:17];
            label.font = [UIFont boldSystemFontOfSize:14];
            [headerView addSubview:label];
        }
        
        view = headerView;
        
    }else if (section == 1) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
        headerView.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 30)];
        label.text = @"推荐更多我去过的目的地,帮助穷游er";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor lightGrayColor];
        label.font = [UIFont systemFontOfSize:15];
        label.font = [UIFont boldSystemFontOfSize:12];
        [headerView addSubview:label];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(300, 0, 20, 40)];
        imgView.image = [UIImage imageNamed:@"myLastMin_arrow@2x"];
        [headerView addSubview:imgView];
        
        view = headerView;
    }
    else if (section == 2) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 20)];
        label.text = @"发现下一站";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:17];
        label.font = [UIFont boldSystemFontOfSize:14];
        [headerView addSubview:label];
        
        view = headerView;
    }else if (section == 3) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 150)];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
        label.text = @"抢特价折扣";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:17];
        label.font = [UIFont boldSystemFontOfSize:14];
        [headerView addSubview:label];
        
        UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        btn1.frame = CGRectMake(0, 20, WIDTH, 120);
        [btn1 sd_setBackgroundImageWithURL:[NSURL URLWithString:_discountSubArray[0][@"photo"]] forState:UIControlStateNormal];
        [btn1 addTarget:self action:@selector(ADButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:btn1];
        
        view = headerView;
    }else {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 20)];
        label.text = @"热门推荐";
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.font = [UIFont systemFontOfSize:17];
        label.font = [UIFont boldSystemFontOfSize:14];
        [headerView addSubview:label];
        
        view = headerView;
    }
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 20)];
    footerView.backgroundColor = [UIColor grayColor];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 250;
    }else if (section == 1) {
        return 40;
    }else if (section == 2) {
        return 30;
    }else if (section == 3) {
        return 150;
    }else {
        return 30;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 20;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else if (section == 1) {
        return 0;
    }else if (section == 2) {
        return 3;
    }else if (section == 3) {
        return 3;
    }else {
        return _otherArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            return 120;
        }else if (indexPath.row == 1) {
            return 100;
        }else{
            return 40;
        }
    }else if (indexPath.section == 3){
        if (indexPath.row == 2) {
            return 40;
        }
        return 160;
    }else {
        return 100;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            OneTableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"one"];
            [iCell.imgView sd_setImageWithURL:[NSURL URLWithString:_subjectArray[0][@"photo"]]];

            cell = iCell;
        }else if (indexPath.row == 1){
            TwoTableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"two"];
            [iCell.oneImgView sd_setImageWithURL:[NSURL URLWithString:_subjectArray[1][@"photo"]]];
            [iCell.twoImgView sd_setImageWithURL:[NSURL URLWithString:_subjectArray[2][@"photo"]]];

            cell = iCell;
        }else {
            UITableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"zero"];
            iCell.textLabel.text = @"查看全部";
            iCell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell = iCell;
            
        }
        
    }else if (indexPath.section == 3) {
        if (indexPath.row == 0) {
            ThreeTableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"three"];
            
            DiscountObject *obj1 = _discountArray[0];
            DiscountObject *obj2 = _discountArray[1];
            
            [iCell.oneImgView sd_setImageWithURL:[NSURL URLWithString:obj1.photo]];
            iCell.oneTitleLabel.text = obj1.title;
            iCell.oneDiscountLabel.text = obj1.priceoff;
            iCell.onePriceLabel.text = obj1.price;
           
            NSString *str1 = obj1.price;
            NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[str1 componentsSeparatedByString:@"<em>"]];
            [arr1 addObjectsFromArray:[arr1[1] componentsSeparatedByString:@"</em>"]];
            iCell.onePriceLabel.text = [NSString stringWithFormat:@"%@%@",arr1[2],arr1[3]];

            [iCell.twoImgView sd_setImageWithURL:[NSURL URLWithString:obj2.photo]];
            iCell.twoTitleLabel.text = obj2.title;
            iCell.twoDiscountLabel.text = obj2.priceoff;
            iCell.twoPriceLabel.text = obj2.price;

            NSString *str2 = obj2.price;
            NSMutableArray *arr2 = [NSMutableArray arrayWithArray:[str2 componentsSeparatedByString:@"<em>"]];
            [arr2 addObjectsFromArray:[arr2[1] componentsSeparatedByString:@"</em>"]];
            iCell.twoPriceLabel.text = [NSString stringWithFormat:@"%@%@",arr2[2],arr2[3]];

            cell = iCell;
        }else if (indexPath.row == 1) {
            ThreeTableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"three"];
            
            DiscountObject *obj1 = _discountArray[2];
            DiscountObject *obj2 = _discountArray[3];
            
            [iCell.oneImgView sd_setImageWithURL:[NSURL URLWithString:obj1.photo]];
            iCell.oneTitleLabel.text = obj1.title;
            iCell.oneDiscountLabel.text = obj1.priceoff;
            
            NSString *str1 = obj1.price;
            NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[str1 componentsSeparatedByString:@"<em>"]];
            [arr1 addObjectsFromArray:[arr1[1] componentsSeparatedByString:@"</em>"]];
            iCell.onePriceLabel.text = [NSString stringWithFormat:@"%@%@",arr1[2],arr1[3]];
            
            [iCell.twoImgView sd_setImageWithURL:[NSURL URLWithString:obj2.photo]];
            iCell.twoTitleLabel.text = obj2.title;
            iCell.twoDiscountLabel.text = obj2.priceoff;
            
            NSString *str2 = obj2.price;
            NSMutableArray *arr2 = [NSMutableArray arrayWithArray:[str2 componentsSeparatedByString:@"<em>"]];
            [arr2 addObjectsFromArray:[arr2[1] componentsSeparatedByString:@"</em>"]];
            iCell.twoPriceLabel.text = [NSString stringWithFormat:@"%@%@",arr2[2],arr2[3]];
         
            cell = iCell;
        }else {
            UITableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"zero"];
            iCell.textLabel.text = @"查看全部";
            iCell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell = iCell;
        }
        
    }
    else{
        FourTableViewCell *iCell = [tableView dequeueReusableCellWithIdentifier:@"four"];
        
        TravelObject *obj = _otherArray[indexPath.row];
        [iCell.imgView sd_setImageWithURL:[NSURL URLWithString:obj.photo]];
        iCell.titleLabel.text = obj.title;
        iCell.authorLabel.text = obj.username;
        iCell.replysLabel.text = [NSString stringWithFormat:@"评论:%@",obj.replys];
        iCell.readTimesLabel.text = [NSString stringWithFormat:@"已读:%@",obj.views];
        
        cell = iCell;
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelObject *obj = _otherArray[indexPath.row];

    SkimWebViewController *skimVC = [[SkimWebViewController alloc] init];
    skimVC.http = obj.view_author_url;
    [self.controller.navigationController pushViewController:skimVC animated:YES];
    
//    tableView.
}

@end
